package com.example.framework.security.core.decoder;

import cn.hutool.core.util.ObjectUtil;
import com.example.framework.security.config.SecurityProperties;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;

public class FeignTokenDecoder extends SpringDecoder implements Decoder {

    private final SecurityProperties securityProperties;

    public FeignTokenDecoder(ObjectFactory<HttpMessageConverters> messageConverters, SecurityProperties securityProperties) {
        super(messageConverters);
        this.securityProperties = securityProperties;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletResponse httpServletResponse = requestAttributes.getResponse();
            if (httpServletResponse != null) {
                // 添加 响应头
                Collection<String> jwtToken = response.headers().get(securityProperties.getHeaderName());
                if (ObjectUtil.isNotEmpty(jwtToken)) {
                    jwtToken.forEach(token -> httpServletResponse.addHeader(securityProperties.getHeaderName(), token));
                }
                // 添加 cookie
                Collection<String> cookies = response.headers().get(HttpHeaders.SET_COOKIE);
                if (ObjectUtil.isNotEmpty(cookies)) {
                    cookies.forEach(cookie -> httpServletResponse.addHeader(HttpHeaders.SET_COOKIE, cookie));
                }
            }
        }
        return super.decode(response, type);
    }
}
